/* Copyright (c) 2010, mitsuhisa.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of the misuhisa.net nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef NYU_VALUE_HPP_
#define NYU_VALUE_HPP_

#include <cassert>

namespace nyu {

class Object;
class Context;

typedef long int_type;
typedef double float_type;
typedef long Value;
typedef Value (*func_type)(Context&);

const Value NULL_VALUE = 1;

enum ValueTag {
    VALUE_TAG_INT, VALUE_TAG_OBJECT,
};

enum ValueTag2 {
    VALUE_TAG_INT_INT,
    VALUE_TAG_INT_OBJECT,
    VALUE_TAG_OBJECT_INT,
    VALUE_TAG_OBJECT_OBJECT,
};

inline ValueTag value_tag(Value value) {
    return ValueTag(value & 1);
}

inline ValueTag2 value_tag(Value v1, Value v2) {
    return ValueTag2((v1 & 1) << 1 | (v2 & 1));
}

inline bool is_int(Value value) {
    return (value & 1) == 0;
}

inline bool is_object(Value value) {
    return (value & 1) == 1;
}

inline bool is_null(Value value) {
    return value == NULL_VALUE;
}

inline Value int_to_value(int_type i) {
    assert((i >= 0 && i <= (i << 1)) || (i < 0 && i > (i << 1)));

    return (i << 1);
}

inline Value object_to_value(Object* p) {
    assert(p == 0 || (reinterpret_cast<Value>(p) & 1) == 0);

    return (reinterpret_cast<Value> (p) | 1);
}

inline int_type value_to_int(Value value) {
    assert(is_int(value));

    return value >> 1;
}

inline Object* value_to_object(Value value) {
    assert(is_object(value));

    return reinterpret_cast<Object*> (value ^ 1);
}

}

#endif /* NYU_VALUE_HPP_ */
